<template>
  <div class="org-management-container">
    <el-card shadow="never" style="margin: 16px;height: 85vh;">
      <vxe-split height="700px" border padding>
        <!-- 左侧：组织架构树 -->
        <vxe-split-pane width="240" min-width="180">
          <div class="tree-wrapper">
            <div class="tree-header">组织架构</div>
            <vxe-tree
              ref="treeRef"
              v-model:current-node="currentNode"
              v-bind="treeOptions"
              v-on="treeEvents"
              style="padding: 10px 0"
            ></vxe-tree>
          </div>
        </vxe-split-pane>

        <!-- 右侧：员工列表 -->
        <vxe-split-pane min-width="400">
          <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
            <!-- 自定义操作列 -->
            <template #operate="{ row }">
              <vxe-button
                v-for="btn in inTableButtons"
                :key="btn.code"
                size="small"
                :status="btn.status"
                mode="text"
                :icon="getButtonIcon(btn.code)"
                @click="
                  handleRowAction(btn.code, row, {
                    openEditPopup: handleEdit,
                    removeRow: handleDelete,
                  })
                "
                :content="btn.name"
              ></vxe-button>
              <!-- <vxe-button
                mode="text"
                status="primary"
                icon="vxe-icon-edit"
                @click="editRow(row)"
                content="编辑"
              ></vxe-button>-->
              <vxe-button
                mode="text"
                status="danger"
                icon="vxe-icon-delete"
                @click="handleDelete(row)"
                content="删除"
              ></vxe-button>
            </template>
          </vxe-grid>
        </vxe-split-pane>
      </vxe-split>
    </el-card>

    <!-- 编辑弹窗 -->
    <vxe-modal
      v-model="editDialogVisible"
      :title="editDialogTitle"
      width="60%"
      :esc-closable="false"
      :mask-closable="false"
      show-footer
    >
      <template #default>
        <vxe-form
          ref="editFormRef"
          v-bind="formOptions"
          :rules="editFormRules"
        ></vxe-form>
        <!-- <vxe-form ref="editFormRef" :data="editFormData" :rules="editFormRules">
          <vxe-form-item field="username" title="部门" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.username"
                placeholder="请输入部门"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="username" title="工号" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.username"
                placeholder="请输入工号"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="realname" title="姓名" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.realname"
                placeholder="请输入姓名"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="realname" title="员工卡号" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.realname"
                placeholder="请输入"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="密码" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="岗位" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入岗位"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="status" title="是否在职" :span="12">
            <template #default>
              <vxe-select
                v-model="editFormData.status"
                placeholder="请选择状态"
              >
                <vxe-option value="0" label="在职"></vxe-option>
                <vxe-option value="1" label="离职"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="mobile" title="手机号" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.mobile"
                placeholder="请输入手机号"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="排序" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="设置角色" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="订阅消息" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入岗位"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="position" title="描述" :span="12">
            <template #default>
              <vxe-input
                v-model="editFormData.position"
                placeholder="请输入"
              ></vxe-input>
            </template>
          </vxe-form-item>
        </vxe-form> -->
      </template>
      <template #footer>
        <vxe-button @click="editDialogVisible = false">取消</vxe-button>
        <vxe-button status="primary" @click="handleEditSubmit">确定</vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { useRoute } from "vue-router";
import XEUtils from "xe-utils";
import {
  getUserTree,
  getQueryMapPage,
  saveTreeEntity,
  delEntityById,
  getRolesByUserId,
  getMsgTemplatesByUserId,
} from "@/api";
import type {
  VxeTreeInstance,
  VxeTreeListeners,
  VxeTreeProps,
  VxeFormInstance,
  VxeFormProps,
} from "vxe-pc-ui";
import type {
  VxeGridListeners,
  VxeGridProps,
  VxeGridInstance,
  VxeFormRules,
} from "vxe-table";
import { ElMessage, ElMessageBox } from "element-plus";
import { permToButtons, splitButtonsByLocation } from "@/utils/permission";
import { useTableActions,setupToolbar } from "@/utils/useTableActions";

// ================== 类型定义 ==================
interface OrgNode {
  id: string;
  title: string;
  parentId?: string | null;
  children?: OrgNode[];
  spread?: boolean;
  open?: boolean;
}

interface TreeOption {
  value: string | number;
  label: string;
  disabled?: boolean;
  children?: TreeOption[];
}

interface EmployeeVO {
  id: string;
  username: string;
  realname: string;
  deptName: string;
  status: string;
  mobile?: string;
  position?: string;
  createTime: string;
  [key: string]: any;
}

interface SearchParams {
  username?: string;
  realname?: string;
  deptId?: string;
  pageNumber: number;
  pageSize: number;
}

// ================== 响应式数据 ==================
const route = useRoute();
const treeRef = ref<VxeTreeInstance<OrgNode>>();
const xGrid = ref<VxeGridInstance<EmployeeVO>>();
const editFormRef = ref<VxeFormInstance>();
const vuePermission = ref<any[]>([]);
const currentNode = ref<OrgNode | null>(null);
const treeData = ref<OrgNode[]>([]);
const inTableButtons = ref<any[]>([]);
// 存储原始角色数据
const roleData = ref<any[]>([]);
const msgTemplatesBy = ref<any[]>([]);

// 分页和搜索参数
const pageSize = ref(10);
const currentPage = ref(1);
const totalCount = ref(0);
const firstSegment = ref("");
const lastSegment = ref("");

// 编辑相关
const editDialogVisible = ref(false);
const editDialogTitle = ref("");
const currentEditRow = ref<EmployeeVO | null>(null);
const editFormData = ref({
  id: "",
  username: "", // 工号 or 部门名称（根据上下文）
  realname: "",
  mobile: "",
  position: "",
  status: "0",
  deptName: "",
  parentId: null,
  idCard: "",
  password: "",
  sort: 0,
  remarks: "",
  roleIds: [], // string[] 或 number[]
  subscribeMsg: false,
});
// 表单数据

// 编辑表单验证规则
const editFormRules = reactive<VxeFormRules>({
  username: [{ required: true, message: "工号不能为空" }],
  realname: [{ required: true, message: "姓名不能为空" }],
  position: [{ required: true, message: "岗位不能为空" }],
  deptName: [{ required: true, message: "部门不能为空" }],
});

// 搜索表单数据
const searchForm = reactive({
  username: "",
  realname: "",
});

// 树配置
const treeOptions = reactive<VxeTreeProps<OrgNode>>({
  data: [],
  keyField: "id",
  size: "mini",
  parentField: "parentId",
  titleField: "title",
  nodeConfig: {
    isHover: true,
    isCurrent: true,
  },
  expandAll: true,
});

// 表格配置 - 添加行内编辑功能
const gridOptions = reactive<VxeGridProps<EmployeeVO>>({
  border: true,
  loading: false,
  size: "mini",
  showOverflow: true,
  height: "100%",
  keepSource: true,
   printConfig: {},
  importConfig: {},
  exportConfig: {},
  // 编辑配置
  // editConfig: {
  //   trigger: 'click',
  //   mode: 'row',
  //   showStatus: true,
  //   autoClear: false
  // },
  // 分页配置
  pagerConfig: {
    enabled: true,
    pageSize: pageSize.value,
    currentPage: currentPage.value,
    total: totalCount.value,
    pageSizes: [10, 20, 50, 100],
    layouts: [
      "PrevJump",
      "PrevPage",
      "Number",
      "NextPage",
      "NextJump",
      "Sizes",
      "FullJump",
      "Total",
    ],
  },
  // 工具栏配置
  toolbarConfig: {
    buttons: [],
  },
  // 搜索表单配置
  formConfig: {
    data: searchForm,
    items: [
      {
        field: "username",
        title: "工号",
        span: 6,
        itemRender: { name: "VxeInput", props: { placeholder: "请输入工号" } },
      },
      {
        field: "realname",
        title: "姓名",
        span: 6,
        itemRender: { name: "VxeInput", props: { placeholder: "请输入姓名" } },
      },
      {
        align: "center",
        itemRender: {
          name: "VxeButtonGroup",
          options: [
            { type: "submit", content: "搜索", status: "primary" },
            { type: "reset", content: "重置" },
          ],
        },
      },
    ],
  },
  columns: [
    { type: "checkbox", width: 60 },
    // { type: "seq", width: 60, title: "序号" },
    {
      field: "deptName",
      title: "所属部门",
      minWidth: 120,
      editRender: { name: "input" },
    },
    {
      field: "username",
      title: "工号",
      minWidth: 80,
      editRender: { name: "input" },
    },
    {
      field: "realname",
      title: "姓名",
      minWidth: 100,
      sortable: true,
      editRender: { name: "input" },
    },
    {
      field: "mobile",
      title: "手机号",
      minWidth: 120,
      editRender: { name: "input" },
    },
    {
      field: "status",
      title: "状态",
      minWidth: 80,
      formatter: ({ cellValue }) => (cellValue === "0" ? "在职" : "离职"),
      editRender: {
        name: "select",
        options: [
          { value: "0", label: "在职" },
          { value: "1", label: "离职" },
        ],
      },
    },
    {
      field: "position",
      title: "岗位",
      minWidth: 100,
      editRender: { name: "input" },
    },
    {
      field: "createTime",
      title: "创建时间",
      minWidth: 160,
      sortable: true,
      formatter: ({ cellValue }) =>
        XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:mm"),
    },
    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: { default: "operate" },
    },
  ],
  data: [],
});

// ================== 事件处理 ==================
const gridEvents: VxeGridListeners = {
  // 表单提交（搜索）
  formSubmit({ data }) {
    console.log("搜索参数:", data);
    Object.assign(searchForm, data);
    currentPage.value = 1;
    loadEmployeeList();
  },

  // 表单重置
  formReset() {
    console.log("表单重置");
    Object.assign(searchForm, {
      username: "",
      realname: "",
    });
    currentPage.value = 1;
    loadEmployeeList();
  },

  // 分页变化
  pageChange({ currentPage: page, pageSize: size }) {
    console.log("分页变化:", { page, size });
    currentPage.value = page;
    pageSize.value = size;
    loadEmployeeList();
  },

  // 工具栏按钮点击
  toolbarButtonClick({ code }) {
    console.log("工具栏按钮:", code);
    switch (code) {
      case "add":
        handleAdd();
        break;
      case "del":
        handleBatchDelete();
        break;
      case "myExport":
        handleExport();
        break;
      case "mySave":
        handleSave();
        break;
    }
  },

  // 编辑事件
  editClosed({ row, column }) {
    console.log("编辑关闭", row, column);
  },
};

const { getButtonIcon, handleRowAction } = useTableActions<RowVO>({
  customAction(row) {
    console.log("自定义操作:", row.name);
  },
});
// ================== 业务方法 ==================
// 构建请求参数
const buildRequestParams = (): SearchParams => {
  const params: SearchParams = {
    pageNumber: currentPage.value,
    pageSize: pageSize.value,
  };

  if (currentNode.value && currentNode.value.id !== "ROOT") {
    params.deptId = currentNode.value.id;
  }

  if (searchForm.username) {
    params.username = searchForm.username;
  }
  if (searchForm.realname) {
    params.realname = searchForm.realname;
  }

  return params;
};

// 加载员工列表
const loadEmployeeList = async () => {
  if (!currentNode.value) {
    gridOptions.data = [];
    return;
  }

  gridOptions.loading = true;
  try {
    const pathSegments = route.path.split("/").filter(Boolean);
    const permissions = route.meta.permission || [];
    const allButtons = permToButtons(permissions);
    const { toolbarButtons, inTableButtons: ops } =
      splitButtonsByLocation(allButtons);

    vuePermission.value = toolbarButtons;
    inTableButtons.value = ops; // 存入响应式变量
    firstSegment.value = pathSegments[0] || "";
    lastSegment.value = pathSegments.pop() || "";

    const params = buildRequestParams();

    const response = await getQueryMapPage(lastSegment.value, params);

    if (response && response.data) {
      gridOptions.data =
        response.data.list || response.data.records || response.data;
     gridOptions.toolbarConfig = setupToolbar(vuePermission.value);
      totalCount.value = response.data.total || response.data.totalCount || 0;

      if (gridOptions.pagerConfig) {
        gridOptions.pagerConfig.total = totalCount.value;
        gridOptions.pagerConfig.currentPage = currentPage.value;
        gridOptions.pagerConfig.pageSize = pageSize.value;
      }
    } else {
      gridOptions.data = [];
      totalCount.value = 0;
    }
  } catch (err) {
    console.error("加载员工失败:", err);
    gridOptions.data = [];
    totalCount.value = 0;
    ElMessage.error("加载员工数据失败");
  } finally {
    gridOptions.loading = false;
  }
};

// 刷新数据
const handleRefresh = () => {
  console.log("刷新数据");
  loadEmployeeList();
};

const getMsgTemplates = async (userId) => {
  const MsgTemplates = await getMsgTemplatesByUserId({ userId });
  msgTemplatesBy.value = MsgTemplates;
};
// 新增员工
const handleAdd = () => {
  console.log("新增员工");
  editDialogTitle.value = "新增员工";
  currentEditRow.value = null;
  getMsgTemplates(null);
  // 重置表单数据
  Object.assign(formOptions.data, {
    id: "",
    username: "",
    realname: "",
    mobile: "",
    position: "",
    status: "0",
  });

  editDialogVisible.value = true;

  nextTick(() => {
    editFormRef.value?.clearValidate();
  });
};

// 编辑行
const handleEdit = (row: EmployeeVO) => {
  console.log("编辑行:", row);
  editDialogTitle.value = "编辑员工";
  currentEditRow.value = row;
  getMsgTemplates(row.userId);
  // 填充表单数据
  Object.assign(formOptions.data, {
    // id: row.id,
    // username: row.username,
    // realname: row.realname,
    // mobile: row.mobile || "",
    // position: row.position || "",
    // status: row.status || "0",
    parentId: row.deptId,
    ...row,
  });

  editDialogVisible.value = true;

  nextTick(() => {
    editFormRef.value?.clearValidate();
  });
};

// 删除行
const handleDelete = async (row: EmployeeVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除员工 "${row.realname}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 调用删除API
    const result = await delEntityById(lastSegment.value, { ids: row.id });

    if (result.code === 0) {
      ElMessage.success("删除成功");
      loadEmployeeList(); // 重新加载数据
    } else {
      ElMessage.error(result.message || "删除失败");
    }
  } catch (error) {
    console.log("取消删除");
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (!xGrid.value) return;

  const selectedRows = xGrid.value.getCheckboxRecords();
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择要删除的员工");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.length} 名员工吗？`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.map((row) => row.id).join(",");
    const result = await delEntityById(lastSegment.value, { ids });

    if (result.code === 0) {
      ElMessage.success(`成功删除 ${selectedRows.length} 名员工`);
      loadEmployeeList();
    } else {
      ElMessage.error(result.message || "批量删除失败");
    }
  } catch (error) {
    console.log("取消批量删除");
  }
};

// 保存编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value) return;

  const isValid = await editFormRef.value.validate();
  console.log(isValid);
  if (!isValid) {
    ElMessage.warning("请填写完整信息");
    return;
  }

  try {
    const submitData = { ...editFormData };

    // 调用保存API
    const result = await saveTreeEntity(lastSegment.value, submitData);

    if (result.code === 0) {
      ElMessage.success(editDialogTitle.value + "成功");
      editDialogVisible.value = false;
      loadEmployeeList(); // 重新加载数据
    } else {
      ElMessage.error(result.message || "操作失败");
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 保存行内编辑
const handleSave = async () => {
  if (!xGrid.value) return;

  const { insertRecords, removeRecords, updateRecords } =
    xGrid.value.getRecordset();

  if (updateRecords.length === 0 && insertRecords.length === 0) {
    ElMessage.warning("没有需要保存的数据");
    return;
  }

  try {
    // 处理更新记录
    for (const record of updateRecords) {
      await saveTreeEntity(lastSegment.value, record);
    }

    // 处理新增记录（如果有的话）
    // for (const record of insertRecords) {
    //   await createEntity(lastSegment.value, record);
    // }

    ElMessage.success("保存成功");
    xGrid.value.clearEdit(); // 清除编辑状态
    loadEmployeeList(); // 重新加载数据确保一致性
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 导出数据
const handleExport = () => {
  console.log("导出数据");
  if (xGrid.value) {
    xGrid.value.exportData({
      filename: "员工列表",
      sheetName: "员工数据",
      type: "xlsx",
    });
  }
};

// 树事件
const treeEvents: VxeTreeListeners<OrgNode> = {
  currentChange({ node }) {
    console.log("树节点切换:", node);
    currentNode.value = node;
    currentPage.value = 1;
    loadEmployeeList();
  },
};

const formatTreeForSelect = (
  nodes: OrgNode[],
  parentId: string | null = null
): any[] => {
  let list: any[] = [];
  nodes.forEach((node) => {
    const { id, title } = node;
    list.push({
      id,
      title,
      parentId,
      disabled: id === editFormData.id, // 防止自己选自己作为父级
    });

    if (node.children && node.children.length > 0) {
      list = list.concat(formatTreeForSelect(node.children, id));
    }
  });
  return list;
};
const isChildOrSelf = (
  nodes: OrgNode[],
  sourceId: string | number,
  targetId: string | number | null | undefined
): boolean => {
  // 如果 targetId 是 null/undefined，说明是根节点，不可能是子节点
  if (targetId == null) return false;

  for (const node of nodes) {
    if (node.id == targetId) return true; // 找到目标，返回 true
    if (node.id == sourceId) continue;
    if (node.children?.length) {
      if (isChildOrSelf(node.children, sourceId, targetId)) return true;
    }
  }
  return false;
};

const treeSelectOptions = computed(() => {
  const currentId = editFormData.value.id; // 当前编辑项 ID

  const buildOptions = (nodes: OrgNode[]): TreeOption[] => {
    return nodes.map((node) => ({
      value: node.id,
      label: node.title,
      disabled: currentId
        ? isChildOrSelf(treeData.value, currentId, node.id)
        : false,
      children:
        node.children && node.children.length > 0
          ? buildOptions(node.children)
          : undefined,
    }));
  };

  return buildOptions(treeData.value);
});
const roleOptions = computed(() => {
  return roleData.value.map((role) => ({
    label: role.name,
    content: role.id,
  }));
});
// 编辑表单配置（使用 vxe-form 的 options 模式）
const formOptions = reactive<VxeFormProps<EmployeeVO>>({
  data: editFormData.value, // 注意：editFormData 是 reactive 对象，不需要 .value
  items: [
    {
      field: "parentId",
      title: "部门",
      span: 12,
      itemRender: {
        name: "VxeTreeSelect",
        options: treeSelectOptions.value,
        props: {
          placeholder: "请选择部门",
          clearable: true,
          multiple: false,
          // ⚠️ 你需要确保 treeData 已传入 VxeTreeSelect 组件，或通过插槽处理
        },
      },
    },
    {
      field: "realname",
      title: "姓名",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { placeholder: "请输入真实姓名" },
      },
    },
    {
      field: "username",
      title: "工号",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { placeholder: "请输入工号", clearable: true },
      },
    },
    {
      field: "idCard",
      title: "员工卡号",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { placeholder: "请输入员工卡号" },
      },
    },
    {
      field: "password",
      title: "登录密码",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { type: "password", placeholder: "请输入登录密码" },
      },
    },
    {
      field: "position",
      title: "岗位",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { placeholder: "请输入岗位名称" },
      },
    },
    {
      field: "mobile",
      title: "手机号",
      span: 12,
      itemRender: {
        name: "VxeInput",
        props: { placeholder: "请输入手机号", clearable: true },
      },
    },
    {
      field: "sort",
      title: "排序",
      span: 12,
      itemRender: {
        name: "VxeNumberInput",
        props: { min: 0, max: 999, placeholder: "请输入排序值" },
      },
    },
    {
      field: "status",
      title: "是否在职",
      span: 12,
      itemRender: {
        name: "VxeSelect",
        options: [
          { value: "0", label: "在职" },
          { value: "1", label: "离职" },
        ],
        props: {
          placeholder: "请选择状态",
        },
      },
    },
    {
      field: "roleIds",
      title: "设置角色",
      span: 12,
      itemRender: {
        name: "VxeCheckboxGroup",
        props: {
          placeholder: "请选择角色",
          multiple: true,
          clearable: true,
          // ⚠️ 选项需通过 options 或插槽传入
        },
        options: roleOptions.value,
        // 示例静态选项（实际应从 API 获取）
        // options: [{ value: 'admin', label: '管理员' }, { value: 'user', label: '普通用户' }]
      },
    },
    {
      field: "subscribeMsg",
      title: "订阅消息",
      span: 12,
      itemRender: {
        name: "VxeSwitch",
        props: {
          onLabel: "是",
          offLabel: "否",
        },
      },
    },
    {
      field: "remarks",
      title: "备注",
      span: 24, // 占一整行
      itemRender: {
        name: "VxeTextarea",
        props: {
          autosize: { minRows: 2, maxRows: 4 },
          placeholder: "请输入备注信息",
        },
      },
    },
  ],
});

// 初始化数据
const init = async () => {
  try {
    const orgData = await getUserTree();
    treeOptions.data = Array.isArray(orgData) ? orgData : [];
    treeData.value = Array.isArray(orgData) ? orgData : [];
    if (treeOptions.data.length > 0) {
      const rootNode = treeOptions.data[0];
      currentNode.value = rootNode;
      await loadEmployeeList();
    }
    const roles = await getRolesByUserId();
    roleData.value = roles;
  } catch (err) {
    console.error("初始化失败:", err);
    ElMessage.error("初始化失败");
  }
};
watch(
  treeSelectOptions,
  (newOptions) => {
    const item = formOptions.items?.find((i) => i.field === "parentId");
    if (item?.itemRender) {
      item.itemRender.props = {
        ...item.itemRender.props,
        options: newOptions,
      };
    }
  },
  { immediate: true }
);
watch(
  roleOptions,
  (newOptions) => {
    const item = formOptions.items?.find((i) => i.field === "roleIds");
    if (item?.itemRender) {
      item.itemRender.props = {
        ...item.itemRender.props,
        options: newOptions,
      };
    }
  },
  { immediate: true }
);

// 页面加载时初始化
onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
.org-management-container {
  height: 100%;
}

.tree-wrapper {
  border-right: 1px solid #e6e6e6;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  background-color: #f8f8f8;
  border-bottom: 1px solid #eee;
}

// 确保分页器样式正常
:deep(.vxe-pager) {
  margin-top: 16px;
}

// 确保工具栏样式正常
:deep(.vxe-toolbar) {
  padding: 12px 0;
}

// 编辑状态样式
:deep(.vxe-cell--edit) {
  .vxe-input,
  .vxe-select {
    width: 100%;
  }
}
</style>
